package com.bifang.common.util;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

/**
 * RSA 加密解密<br>
 * 1. 首先服务器生成一个秘钥对(包含publicKey和privateKey), 然后将publicKey交给客户端, 服务器端保存privateKey 2. 客户端, 通过 publicKey
 * 对json进行加密(加密方法 encryptByPublicKey(content, publicKey))得到一个加密的串 encryptString, 将这个
 * encryptString传递给服务器 3. 服务器拿到这个string之后, 首先进行签名验证:
 *
 * @author ly
 */
public class EncryptUtil {

    /** 非对称密钥算法 */
    private static final String KEY_ALGORITHM = "RSA";

    /** 签名算法 */
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /** 密钥长度 */
    private static final int KEY_SIZE = 1024;

    /** 密钥长度 注意明文长度是否超过密文长度减去11字节 */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /** 分块加密长度 */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /** 公钥 */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /** 私钥 */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /** 公钥类型 */
    private static final int PUBLIC_SECRET = 1;

    /** 私钥类型 */
    private static final int PRIVATE_SECRET = 2;

    /**
     * 生成密钥对(公钥和私钥)
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 随机数生成器
        SecureRandom sr = new SecureRandom();
        // 设置秘钥的长度为 KEY_SIZE = 1024
        keyPairGen.initialize(KEY_SIZE, sr);
        // 开始创建
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<>(2);
        // 存储 加密对
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data 已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decodeFromString(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64Utils.encodeToString(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param data 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign 数字签名
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
        byte[] keyBytes = Base64Utils.decodeFromString(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decodeFromString(sign));
    }

    /**
     * 私钥解密
     *
     * @param encryptedData 已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String encryptedData, String privateKey)
            throws Exception {
        if (StringUtils.isBlank(encryptedData)) {
            return encryptedData;
        }
        return processBlock(encryptedData, privateKey, PRIVATE_SECRET, Cipher.DECRYPT_MODE);
    }

    /**
     * 公钥解密
     *
     * @param encryptedData 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String encryptedData, String publicKey)
            throws Exception {
        if (StringUtils.isBlank(encryptedData)) {
            return encryptedData;
        }
        return processBlock(encryptedData, publicKey, PUBLIC_SECRET, Cipher.DECRYPT_MODE);
    }

    /**
     * 公钥加密
     *
     * @param data 源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String data, String publicKey) throws Exception {
        if (StringUtils.isBlank(data)) {
            return data;
        }
        return processBlock(data, publicKey, PUBLIC_SECRET, Cipher.ENCRYPT_MODE);
    }

    /**
     * 私钥加密
     *
     * @param data 源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
        if (StringUtils.isBlank(data)) {
            return data;
        }
        return processBlock(data, privateKey, PRIVATE_SECRET, Cipher.ENCRYPT_MODE);
    }

    /**
     * 分段加密
     *
     * @param dataStr
     * @param key
     * @param keyType 1:公钥，2：私钥
     * @param mode
     * @return
     * @throws Exception
     */
    private static String processBlock(String dataStr, String key, int keyType, int mode)
            throws Exception {
        if (StringUtils.isBlank(dataStr)) {
            return dataStr;
        }
        byte[] keyBytes = Base64Utils.decodeFromString(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Key keySecret = null;
        if (keyType == PUBLIC_SECRET) {
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            keySecret = keyFactory.generatePublic(x509KeySpec);
        }
        if (keyType == PRIVATE_SECRET) {
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            keySecret = keyFactory.generatePrivate(pkcs8KeySpec);
        }
        int maxSize = (mode == Cipher.ENCRYPT_MODE ? MAX_ENCRYPT_BLOCK : MAX_DECRYPT_BLOCK);
        cipher.init(mode, keySecret);
        byte[] data =
                (mode == Cipher.ENCRYPT_MODE
                        ? dataStr.getBytes()
                        : Base64Utils.decodeFromString(dataStr));
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > maxSize) {
                cache = cipher.doFinal(data, offSet, maxSize);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * maxSize;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        if (mode == Cipher.ENCRYPT_MODE) {
            return Base64Utils.encodeToString(encryptedData);
        }
        if (mode == Cipher.DECRYPT_MODE) {
            return new String(encryptedData);
        }
        return null;
    }

    /**
     * 获取私钥 进行base64 转码
     *
     * @param keyMap 密钥对
     * @return
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64Utils.encodeToString(key.getEncoded());
    }

    /**
     * 获取公钥 进行base64 转码
     *
     * @param keyMap 密钥对
     * @return
     */
    public static String getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64Utils.encodeToString(key.getEncoded());
    }

    /**
     * 测试方法
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //        String content = "Hello, world!";
        //        Map<String, Object> keyPair = genKeyPair();
        //        String publicKey = getPublicKey(keyPair);
        //        String privateKey = getPrivateKey(keyPair);
        //        System.out.println("公钥：" + publicKey);
        //        System.out.println("私钥：" + privateKey);
        //        System.out.println("明文：" + content);
        //        String pubKeyEncrypt = encryptByPublicKey(content, publicKey);
        //        String signContent = sign(content.getBytes(), privateKey);
        //        System.out.println("1.私钥加签：" + signContent);
        //        System.out.println("2.验签结果：" + verify(content.getBytes(), publicKey,
        // signContent));
        //        System.out.println("3.公钥加密：" + pubKeyEncrypt);
        //        System.out.println("4.私钥解密：" + decryptByPrivateKey(pubKeyEncrypt, privateKey));
        //        String publicKey1
        // ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCc+Rt+PKkTUy3ZpDLqagt1Xf0BSDtDwKiDWnDi86tNe44TqLO1A7mY4Igxv4Kctai2GzT8malCOmdO3RgmluRR7CgFuWRZzHwlNJhRoHbe9/ux1jAHp5LSaMISz2oAEc9w0pua4lkUkKmUte+UVogm0c9Z3e9QORNnkzUOuzfMjQIDAQAB";
        //        String pubKeyEncrypt1 = encryptByPublicKey("fa8dcf2d92b741b997320d5375dd2545",
        // publicKey1);
        //       System.out.println("5.token加密：" + pubKeyEncrypt1);
        //       String str1
        // ="gaWvlBChDcsUfzdnKiv9l+iaBD/SH9LQJIOEz2FgbNKL+ZIFIdYut9oVVBerOqSALUotohSFKgCWpNK90CYiOItayyqEAOP1Jtmm/u9SHs78hC5zt4XB96nsA+f8u8le8wZGOAmumnLQaxx2IswO7nNvg7zQvsdLe0tN05xjfv4=";
        //       String privKey
        // ="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJz5G348qRNTLdmkMupqC3Vd/QFIO0PAqINacOLzq017jhOos7UDuZjgiDG/gpy1qLYbNPyZqUI6Z07dGCaW5FHsKAW5ZFnMfCU0mFGgdt73+7HWMAenktJowhLPagARz3DSm5riWRSQqZS175RWiCbRz1nd71A5E2eTNQ67N8yNAgMBAAECgYEAkWZJKiBEOGtGwB9RLkM2A+wga6ydgL+XF7yRbhdo6Gd3DgypERW3N71bSkFrWX8HHE+NQCGRX5A7mxg+w5fnOeZmTQUsJXmxiexLqReOZMdptLz9NSJftXbaEEtKy0rJ8yNKYU2Q9pE8b5d9t+hpgMHUPejO+fYkAY1NvSdUAKECQQDs6F8w/egm+Ugv4egkg4F2f/ch2qRtkyNMibkZTCyiBjvneeh2OWIM/2DZngMzu6yIPMFjRIfQuPfk6z84+76pAkEAqZ+b9WDPtKvxovc9eTQIhwssgkBV0nX3Y6SnXjorwNVsi6IDSjz401BBpqEUN0rM+JH+YZ9FZfIHu1j186DBRQJAO7mRVf6M6lZqFngzWBE3MDKukQBX96/idEc8PN5xWh+MNp0LN9Lbnz86oWIumHo10trOPkJmov4esL2F4M3GkQJAEGgayrIxhPU4qx2k+Ys54+4FwRd99ZxpcF7lvWx8/Orn09242b5qBu51Wyura+m1R7m/VCv2p3SwoMNrDsSWzQJBAJf0qsOH07r7G3Yn9HGVMb2j56DHUXznMWMtIXuycIHGtPGFRSL3kxeJiI3Z21QFx9FyBA1Z/rceBXtpu9Dy+Go=";
        //      String str = decryptByPrivateKey(str1, privKey);
        //      System.out.println("5.token解密：" + str);
        String prKey =
                "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCU49SAuT8K1dtx8M8Oo//ZE6ZoOH0n40g64QdxQz5mSdqLgGwffLnRDv6vcM3yDxWdLg2+IE0R4glNyUYH+YZRV0z4dRuJypBtqtbHm3+lAr7VSxgRCIK6asqkkjXdubGLgDfy7KjVnrypaKbISltplaHMOnUSyAY2oQ5tvj4+akC1S8u3/IpLfja/P7oKSLSCyewbKtFCcY9GZU1/iWANra04wPbNseBks2LN2a+5sgbcHjiCgU626staAAQ/Kst26oN7KB8Yfmauur02FUGuwrpdI14QbORR+G03lwapM6O9Ne/Wsm5NljZ8QCuweNgjKFGS2+jRB+rTwFDx+oeDAgMBAAECggEAejkYzd7EELoD3eIHp4YbVfDajv2oSCE8vxDRUjoYNFH2NMRkfeiehS6hBhY9CbM2VARlRakwezip2JAcjBlbGNTom6FOzOtbaptumwdcXnIFhASUKg9peWyHE1fvHif8xn6n7yQ1aL9ZMlx1ZUAdEGzEGGn4h0VqTFgkBxS/9e10NQ08xbdqDnJqxkRT1aCNXJ8dKLbk4KlmaLx8JeD52cpeQ/Ndk4uBRFfO8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tXbcfDPDqP/2ROmaDh9J+NIOuEHcUM+Zknai4BsH3y50Q7+r3DN8g8VnS4NviBNEeIJTclGB/mGUVdM+HUbicqQbarWx5t/pQK+1UsYEQiCumrKpJI13bmxi4A38uyo1Z68qWimyEpbaZWhzDp1EsgGNqEObb4+PmpAtUvLt/yKS342vz+6Cki0gsnsGyrRQnGPRmVNf4lgDa2tOMD2zbHgZLNizdmvubIG3B44goFOturLWgAEPyrLduqDeygfGH5mrrq9NhVBrsK6XSNeEGzkUfhtN5cGqTOjvTXv1rJuTZY2fEArsHjYIyhRktvo0Qfq08BQ8fqHgwIDAQAB";
        String pubKeyEncrypt1 = encryptByPublicKey("12345", puKey);
        System.out.println("5.加密：" + pubKeyEncrypt1);
        String str = decryptByPrivateKey(pubKeyEncrypt1, prKey);
        System.out.println("5.解密：" + str);
    }
}
